package com.atguigu.gmall.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.pay.config.AlipayConfig;
import com.atguigu.gmall.pay.config.properties.AlipayProperties;
import com.atguigu.gmall.pay.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    OrderFeignClient orderFeignClient;
    @Autowired
    AlipayClient alipayClient;
    @Autowired
    AlipayProperties alipayProperties;

    @Override
    public String generatePayPage(Long orderId, Long userId) throws AlipayApiException {

        //1 获取AlipayClient
/*        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl,
                AlipayConfig.app_id,
                AlipayConfig.merchant_private_key,
                "json",
                AlipayConfig.charset,
                AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);*/

        //2 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturn_url());
        alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());
        //3 准备待支付的订单数据  远程调用，获取订单信息
        OrderInfo orderInfo = orderFeignClient.getOrderInfoById(orderId).getData();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String outTradeNo = orderInfo.getOutTradeNo();
        //付款金额
        BigDecimal totalAmount = orderInfo.getTotalAmount();
        //订单名称
        String subject = "尚品汇-订单-" + outTradeNo;
        //商品描述
        String body = orderInfo.getTradeBody();

        //详细：https://opendocs.alipay.com/open/028r8t?scene=22
        Map<String,Object> bizContent = new HashMap<>();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("total_amount", totalAmount);
        bizContent.put("subject", subject);
        bizContent.put("body", body);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //支付宝 自动关单
        String date = DateUtil.formatDate(orderInfo.getExpireTime(),"yyyy-MM-dd HH:mm:ss");
        bizContent.put("time_expire",date);

        alipayRequest.setBizContent(JSON.toJSONString(bizContent));

        //生成支付页面
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;
    }
}
